import $ from 'jquery'
import { colorTheme } from '../graph/theme'

class ColorPicker {
    constructor(config) {
        this.config = config
        this.colorTheme = colorTheme[this.config.theme].node.series
        this.render()
    }
    
    render() {
        let tmplt = '<div class="flow-color-picker-mask"><div class="flow-element color-picker"><ul>'
        for (let i in this.colorTheme) {
            tmplt += `<li class="color-item ${this.config.color === this.colorTheme[i] ? 'active': ''}" _index="${i}" _value="${this.colorTheme[i]}" style="background-color:${this.colorTheme[i]}"></li>`
        }
        tmplt += '</ul></div></div>'
        let $picker = $(tmplt)
        $('body').append($picker)
        $picker.find('.color-picker').css({
            top: $(this.config.element).offset().top,
            left: $(this.config.element).offset().left + $(this.config.element).width()
        })
        let rendered = false
        setTimeout(() => {
            rendered = true
        }, 0)

        $picker.find('li').on('click', event => {
            if (!$(event.target).hasClass('active')) {
                $(event.target).addClass('active').siblings('li').removeClass('active')
                this.config.change && this.config.change($(event.target).attr('_value'), $(event.target).attr('_index'))
            }
            $picker.remove()
        })

        $('body').off('mousedown.flow-color-picker').on('mousedown.flow-color-picker', event => {
            if ($(event.target).closest(".flow-element.color-picker").length == 0 && rendered) {
                $picker.remove()
            }
        })
    }
}

export default ColorPicker